from app import *
from .response import Respon as Res

@app.route('/', methods=['GET','POST'])
def index():
    return render_template('index.html')

@app.route('/readConfig', methods=['POST'])
def readConfig():
    # 获取config 配置
    return cf.read()

@app.route('/saveConfig', methods=['POST'])
def saveConfig():
    # 保存config 配置
    data = request.get_json()
    cf.cf = data
    cf.save()
    return Res.rjson()


@app.route('/readSource', methods=['POST'])
def readSource():
    # 获取 Source 配置
    return sour.read()


@app.route('/saveSource', methods=['POST'])
def saveSource():
    # 保存 Source 配置
    data = request.get_json()
    sour.cf = data
    sour.save()
    return Res.rjson()

@app.route('/pack',methods=['POST'])
def pack():
    # 打包
    # 打开保存文件对话框
    root = tk.Tk()
    root.withdraw()
    root.wm_attributes('-topmost', 1)
    types = [('html文件','.html')]
    file_path = filedialog.asksaveasfilename(title='打包到',filetypes=types,defaultextension='.html')
    root.destroy()
    if file_path:
        with open(file_path,'w',encoding='utf8') as f:
            file = open('app/outfile.html','r',encoding='utf8')
            t = file.read()
            source = sour.read()
            t = t.replace('source:null',f'source:{json.dumps(source)}',1)
            t = t.replace('<title>api管理</title>', f'<title>{source["name"]}</title>', 1)
            t = t.replace('<link rel="icon" href="favicon.ico">','<!-- <link rel="icon" href="favicon.ico"> --><link rel="stylesheet" href="https://unpkg.com/element-ui/lib/theme-chalk/index.css">')
            t = t.replace('src:url(../fonts/element-icons.535877f5.woff) format("woff"),url(../fonts/element-icons.732389de.ttf) format("truetype");','')
            f.write(t)
            file.close()

        return '0'
    else:
        return '-1'


